﻿CREATE PROCEDURE [dbo].[RequisitionDocInsert]
(--Сводная заявка. Состоит из заказов товара у поставщиков
	@DocDate smalldatetime,
	@DocNumber varchar(20),
	@ShiftDepartmentId int,  --код подразделения, для которого формируется заказ
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50)
)
AS
DECLARE @DepartmentUserId int
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int, @intNextId int
	SET NOCOUNT ON

IF (@ShiftDepartmentId Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF @DocNumber Is Null
BEGIN
	exec [dbo].[GetNextDocNumber] 13, @intRet OUT
	SET @DocNumber = cast( @intRet as varchar(20))
END

IF @DocDate Is Null SET @DocDate = dbo.TodayDate() 
ELSE SET @DocDate = dbo.NormalizeDate(@DocDate)

SELECT @DepartmentUserId = Id FROM CD.DepartmentUsers WHERE Login = suser_sname()

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT
--получение значения идентификатора
EXEC @intRet = dbo.GetNextCounterFor 'Documents', @intNextId OUTPUT
IF @intRet <> 0 RETURN @intRet

	SET NOCOUNT OFF;
INSERT INTO [CA].[Documents] (Id, [DocTypeId], [DocDate], [DocNumber], DepartmentUserId, 
ContragentId, ShiftDepartmentId, [Note], [MD], [MW]) 
VALUES (@intNextId, 13,  @DocDate, @DocNumber, @DepartmentUserId, 
0, @ShiftDepartmentId, @Note, @MD, @MW);

SELECT Id, DepartmentId, DocTypeId, DocDate, DocNumber, 
ContragentId, DepartmentUserId, ShiftDepartmentId, Note, MD, MW 
FROM CA.Documents WHERE (Id = @intNextId)

RETURN 0



